package com.managertrade.util;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.StringJoiner;

public class OkxProxyHttpClient {

    private static final String PROXY_HOST = "127.0.0.1";
    private static final int PROXY_PORT = 22307;

    // ✅ 启动时初始化是否走代理
    private static final boolean USE_PROXY = initUseProxy();

    private static boolean initUseProxy() {
        try {
            String targetIp = "192.168.0.100"; // ✅ 替换成你需要走代理的机器 IP
            String localIp = InetAddress.getLocalHost().getHostAddress();
            System.out.println("[OKX-Proxy] 当前IP: " + localIp + " 是否使用代理: " + targetIp.equals(localIp));
            return targetIp.equals(localIp);
        } catch (Exception e) {
            System.err.println("[OKX-Proxy] 获取本机 IP 失败，默认不使用代理");
            return false;
        }
    }


    public static boolean isUseProxy() {
        return USE_PROXY;
    }

    // ✅ GET 请求
    public static String get(String baseUrl, Map<String, String> queryMap) throws Exception {
        StringJoiner paramJoiner = new StringJoiner("&");
        if (queryMap != null) {
            for (Map.Entry<String, String> entry : queryMap.entrySet()) {
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                    paramJoiner.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" +
                            URLEncoder.encode(entry.getValue(), "UTF-8"));
                }
            }
        }
        String fullUrl = baseUrl + (paramJoiner.length() > 0 ? "?" + paramJoiner : "");
        HttpURLConnection conn = openConnection(fullUrl);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");
        setCommonHeaders(conn);

        int status = conn.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("GET 请求失败，状态码：" + status);
        }

        return readResponse(conn);
    }
    public static String getUserHead(String baseUrl, Map<String, String> headers) throws Exception {
        String fullUrl = baseUrl;
        HttpURLConnection conn = openConnection(fullUrl);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");
        setCommonHeaders(conn);
        // 额外的 header，比如 OKX 的认证头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("GET 请求失败，状态码：" + status);
        }

        return readResponse(conn);
    }
    // ✅ POST 请求（JSON 请求体）
    public static String postJson(String urlStr, String jsonBody) throws Exception {
        HttpURLConnection conn = openConnection(urlStr);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        setCommonHeaders(conn);
        conn.setRequestProperty("Content-Type", "application/json");

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
            os.write(input);
        }

        int status = conn.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("POST 请求失败，状态码：" + status);
        }

        return readResponse(conn);
    }

    // ✅ POST 请求（带 headers）
    public static String postJson(String urlStr, String jsonBody, Map<String, String> headers) throws Exception {
        HttpURLConnection conn = openConnection(urlStr);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
            os.write(input);
        }

        int status = conn.getResponseCode();
        if (status != 200) {
            try (BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder error = new StringBuilder();
                String line;
                while ((line = errorReader.readLine()) != null) {
                    error.append(line);
                }
                throw new RuntimeException("POST 请求失败，状态码：" + status + "，错误信息：" + error);
            }
        }

        return readResponse(conn);
    }

    // ✅ 封装连接创建，自动判断是否走代理
    private static HttpURLConnection openConnection(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        if (USE_PROXY) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
            return (HttpURLConnection) url.openConnection(proxy);
        } else {
            return (HttpURLConnection) url.openConnection();
        }
    }

    // ✅ 通用请求头
    private static void setCommonHeaders(HttpURLConnection conn) {
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Referer", "https://www.okx.com/");
    }

    // ✅ 响应读取
    private static String readResponse(HttpURLConnection conn) throws IOException {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }


}
